package io.renren.softpark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.app.dao.UserDao;
import io.renren.softpark.dao.*;
import io.renren.softpark.dto.*;
import io.renren.softpark.service.UserMyService;
import io.renren.softpark.entity.*;
import io.renren.softpark.service.*;
import io.renren.softpark.util.RedisUtil;
import io.swagger.models.auth.In;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Cui
 * @Date: 2020/8/23
 * @Description:
 */
@Service("homeService")
public class HomeServiceImpl implements HomeService {

    private ApplicationContext applicationContext;

    @Autowired
    UserDao userDao;
    @Autowired
    PlatesDao platesDao;
    @Autowired
    IntroduceDao introduceDao;

    @Autowired
    SortDao sortDao;
    @Autowired
    CommentService commentService;

    @Autowired
    SoftwareService softwareService;

    @Autowired
    UserMyService userMyService;

    @Autowired
    FeedService feedService;

    @Autowired
    ColumnService columnService;

    @Autowired
    ColumnDao columnDao;

    @Autowired
    SoftwareDao softwareDao;

    @Autowired
    CommentDao commentDao;

    @Autowired
    RecordDao recordDao;

    @Autowired
    UserMyDao useDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<WebOverview> getWebOverview(){
        List<WebOverview> lists = new ArrayList<>();
        //封装软件新增和累计
        List<SoftwareEntity> softList = softwareService.list();
        List<SoftwareEntity> collect = softList.stream().filter((l) ->
                new SimpleDateFormat("yyyy-MM-dd").format(l.getCreateTime())
                        .equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
        ).collect(Collectors.toList());
        WebOverview softOverview = new WebOverview();
        softOverview.setAddNums(collect.size());
        softOverview.setAllNums(softList.size());
        lists.add(softOverview);
        //封装用户新增和累计
        List<UserEntity> userList = userMyService.list();
        List<UserEntity> collect1 = userList.stream().filter((u) ->
                new SimpleDateFormat("yyyy-MM-dd").format(u.getCreateTime())
                        .equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
        ).collect(Collectors.toList());
        WebOverview userOverview = new WebOverview();
        userOverview.setAddNums(collect1.size());
        userOverview.setAllNums(userList.size());
        lists.add(userOverview);

        //封装评论新增和反馈
        List<CommentEntity> commentList = commentService.list();
        List<CommentEntity> collect2 = commentList.stream().filter((c) ->
                new SimpleDateFormat("yyyy-MM-dd").format(c.getTime())
                        .equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
        ).collect(Collectors.toList());
        WebOverview commentOverview = new WebOverview();
        commentOverview.setAllNums(commentList.size());
        commentOverview.setAddNums(collect2.size());
        lists.add(commentOverview);
        //封装反馈新增和累计
        List<FeedEntity> feedList = feedService.list();
        List<FeedEntity> collect3 = feedList.stream().filter((f) ->
                new SimpleDateFormat("yyyy-MM-dd").format(f.getTime())
                        .equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
        ).collect(Collectors.toList());
        WebOverview feedOverview = new WebOverview();
        feedOverview.setAllNums(feedList.size());
        feedOverview.setAddNums(collect3.size());
        lists.add(feedOverview);
        return lists;
    }

    @Override
    public int[] getWaitVerify(){
        int[] result = new int[3];
        result[0] = columnDao.selectCount(
                new QueryWrapper<ColumnEntity>().eq("verify", 0));
        result[1] = softwareDao.selectCount(
                new QueryWrapper<SoftwareEntity>().eq("verify", 0));
        result[2] = commentDao.selectCount(
                new QueryWrapper<CommentEntity>().eq("verify", 0));
        return result;
    }

    @Override
    public TendencyDto getTendency(){
        List<RecordEntity> behaviors = recordDao.selectList(
                new QueryWrapper<RecordEntity>());
        List<RecordEntity> downloadCollect = behaviors.stream().filter((b) ->
                b.getBehavior() == 2
        ).collect(Collectors.toList());
        List<RecordEntity> publishCollect = behaviors.stream().filter((b) ->
                b.getBehavior() == 7
        ).collect(Collectors.toList());
        Calendar c = Calendar.getInstance();
        int[] downloads = new int[7];
        int[] publishes = new int[7];
        String[] dates = new String[7];
        for(int i=0;i<7;i++){
            Date temp = c.getTime();
            List<RecordEntity> dCollect = downloadCollect.stream().filter((b) ->
                    new SimpleDateFormat("yyyy-MM-dd").format(b.getCreateTime())
                            .equals(new SimpleDateFormat("yyyy-MM-dd").format(temp))
            ).collect(Collectors.toList());
            List<RecordEntity> pCollect = publishCollect.stream().filter((p) ->
                    new SimpleDateFormat("yyyy-MM-dd").format(p.getCreateTime())
                            .equals(new SimpleDateFormat("yyyy-MM-dd").format(temp))
            ).collect(Collectors.toList());
            c.add(Calendar.DAY_OF_MONTH, -1);
            downloads[6-i] = dCollect.size();
            publishes[6-i] = pCollect.size();
            dates[6-i] = new SimpleDateFormat("dd").format(temp);
        }
        TendencyDto tendencyDto = new TendencyDto();
        tendencyDto.setDates(dates);
        tendencyDto.setDownloads(downloads);
        tendencyDto.setPublishes(publishes);
        tendencyDto.setMonths(new SimpleDateFormat("M").format(new Date())+"月");
        return tendencyDto;
    }

    @Override
    public List<OnLineUserDto> getOnLineUser(){
        //获取到所有用户的key-value
        List<OnLineUserDto> onLineUserDtos = new ArrayList<>();
        try {
            Set<String> keys = redisTemplate.keys("*");
            System.out.println(keys);
            List<String> collect = keys.stream().filter((k) ->
                    //TODO 正则
                    k.matches("^LOGIN_TIME:$")
            ).collect(Collectors.toList());
            System.out.println(collect);

            List<String> userIdList = new ArrayList<>();
            for (String str : collect){
                String temp = str.substring(11,str.length());
                userIdList.add(temp);
            }

            Map<String,String> LoginTimeIDMap = new HashMap<>();
            for (String str : collect){
                String key = str.substring(11,str.length());
                String value = RedisUtil.getValue((StringRedisTemplate) redisTemplate,str);
                LoginTimeIDMap.put(key,value);
            }

            List<UserEntity> userEntities =userMyService.list();

            for (int i = 0 ; i < userIdList.size() ; i ++){
                OnLineUserDto onLineUserDto = new OnLineUserDto();
                onLineUserDto.setUsername(userEntities.get(i).getUsername());
                onLineUserDto.setLoginTime(LoginTimeIDMap.get(userEntities.get(i).getUserId()));
                onLineUserDtos.set(i,onLineUserDto);
            }
        }catch (NullPointerException e){
            return null;
        }
        return onLineUserDtos;
    }


    /**
     * user页面的回显
     * @param userId
     * @return
     */
    @Override
    public PersonalDetailDto getPersonalDetail(String userId) {
        UserEntity userEntity = useDao.selectOne(new QueryWrapper<UserEntity>().eq("USER_ID",userId));
        List<ColumnEntity> columnEntityList = columnDao.selectList(new QueryWrapper<ColumnEntity>().eq("USER_ID",userId));
        List<SoftwareEntity> softwareEntityList = softwareDao.selectList(new QueryWrapper<SoftwareEntity>().eq("USER_ID",userId));
        PersonalDetailDto personalDto = new PersonalDetailDto();
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");

        //对应信息设置
        List<SortEntity> sortEntityList = sortDao.selectList(new QueryWrapper<SortEntity>());
        List<String> sortList = new ArrayList<>();
        sortList.add("sortName:");
        for (SortEntity sortEntity : sortEntityList){
            String sortName = sortEntity.getSortName();
            sortList.add(sortName);
        }

        List<PlatesEntity> platesEntityList = platesDao.selectList(new QueryWrapper<PlatesEntity>());
        List<String> platesList = new ArrayList<>();
        platesList.add("platesName:");
        for (PlatesEntity platesEntity : platesEntityList){
            String platesName = platesEntity.getPlateName();
            platesList.add(platesName);
        }

        Map<String,String> columnSoftMap = new HashMap<>();
        for (ColumnEntity columnEntity :columnEntityList){
            String columnName = columnEntity.getColumnName();
            String columnId = columnEntity.getColumnId();
            columnSoftMap.put(columnId,columnName);
        }
        //赋值用户信息

        personalDto.setUserId(userId);
        personalDto.setUserName(userEntity.getUsername());
        personalDto.setPhone(userEntity.getPhone());
        personalDto.setEmail(userEntity.getEmail());
        String createTime = simpleFormat.format(userEntity.getCreateTime());
        personalDto.setCreateTime(createTime);
        String updateTime = simpleFormat.format(userEntity.getUpdateTime());
        personalDto.setUpdateTime(updateTime);
        personalDto.setPassword(userEntity.getPassword());

        //赋值栏目List属性
        List<PersonalDetailColumnDataDto> columnDataDtoList = new ArrayList<>();
        for (int i = 0 ; i < columnEntityList.size();i++){
            PersonalDetailColumnDataDto columnDataDto = new PersonalDetailColumnDataDto();
            ColumnEntity columnEntity =columnEntityList.get(i);

            columnDataDto.setColumnId(columnEntity.getColumnId());
            columnDataDto.setColumnName(columnEntity.getColumnName());
            columnDataDto.setParentForm(sortList.get(columnEntity.getParentId()));
            columnDataDto.setColumnLogo(columnEntity.getColumnLogo());
            columnDataDto.setColumnWeb(columnEntity.getColumnWeb());
            columnDataDto.setUserName(userEntity.getUsername());
            columnDataDto.setWebIntroduce(columnEntity.getWebIntroduce());
            columnDataDto.setColumnType(columnEntity.getColumnType());
            columnDataDto.setLicense(columnEntity.getLicense());
            columnDataDto.setDetailIntroduce(columnEntity.getIntroduceId());
            columnDataDto.setDownload(columnEntity.getDownloads());
            columnDataDto.setShowPic(columnEntity.getShowPic());
            columnDataDto.setRecommend(columnEntity.getRecommend());
            columnDataDto.setVerify(columnEntity.getVerify());
            columnDataDtoList.add(columnDataDto);
        }
        personalDto.setColumnList(columnDataDtoList);
        //赋值发布过的软件list
        List<PersonalDetailSoftwareDataDto> softwareDataDtoList = new ArrayList<>();
        for(int i = 0 ; i < softwareEntityList.size() ; i ++){
            PersonalDetailSoftwareDataDto softwareDataDto = new PersonalDetailSoftwareDataDto();
            SoftwareEntity  softwareEntity = softwareEntityList.get(i);
            softwareDataDto.setSoftId(softwareEntity.getSoftId());
            softwareDataDto.setSoftName(softwareEntity.getSoftName());
            softwareDataDto.setParentName(columnSoftMap.get(softwareEntity.getParentId()));
            softwareDataDto.setSoftLogo(softwareEntity.getSoftLogo());
            softwareDataDto.setEdition(softwareEntity.getEdition());
            softwareDataDto.setLanguage(softwareEntity.getLanguage());
            softwareDataDto.setPlatform(softwareEntity.getPlatform());
            softwareDataDto.setSoftSize(softwareEntity.getSoftSize());
            softwareDataDto.setSoftAddr(softwareEntity.getSoftAddr());
            softwareDataDto.setSoft_userId(softwareEntity.getUserId());
            softwareDataDto.setSoft_createTime(simpleFormat.format(softwareEntity.getCreateTime()));
            softwareDataDto.setSoft_updateTime(simpleFormat.format(softwareEntity.getUpdateTime()));
            softwareDataDto.setSoft_verify(softwareEntity.getVerify());
            softwareDataDto.setSoft_downloads(softwareEntity.getDownloads());
            softwareDataDto.setSoft_showPic(softwareEntity.getShowPic());
            softwareDataDto.setSoft_briefIntro(softwareEntity.getBriefIntro());

            softwareDataDtoList.add(softwareDataDto);
        }
        personalDto.setSoftwareList(softwareDataDtoList);
        return personalDto;
    }


}
